﻿using Consul;

namespace ELF;

public static class ConsulEx
{
    public static void AddConsulClient(this IHostApplicationBuilder builder, ConsulClient client)
    {
        builder.Services.AddSingleton<IConsulClient>(client);
    }

    public static async Task<string> GetConsulClientAsync(this IHostApplicationBuilder builder, string serviceName)
    {
        var options = builder.Configuration.GetSection(nameof(ConsulOptions)).Get<ConsulOptions>();
        if (options == null)
        {
            throw new ArgumentNullException(nameof(options));
        }
        var client = new ConsulClient(config =>
        {
            var consulAddress = options.Address;
            config.Address = new Uri(consulAddress);
        });

        var queryResult = await client.Health.Service(
            service: serviceName,
            tag: "",          // 可选: 过滤服务标签
            passingOnly: true // 只返回健康实例
        );

        // 随机选择一个健康实例（简单负载均衡）
        var services = queryResult.Response.ToList();
        if (services.Count == 0)
            throw new Exception("No healthy authentication service instances found");

        var serviceEntry = services[new Random().Next(services.Count)];

        // 构造服务地址（考虑处理IPv6地址）
        var host = string.IsNullOrEmpty(serviceEntry.Service.Address)
            ? serviceEntry.Service.Service
            : serviceEntry.Service.Address;

        return $"http://{host}:{serviceEntry.Service.Port}/";
    }
}
